<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Menus &amp; toolbars</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, menu, toolbar, Swing, programming, Jython, Linux">
<meta name="description" content="Menus &amp; toolbars">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Menus &amp; toolbars</h1>

<p>
In this part of the Jython Swing programming tutorial, we will 
work with menus and toolbar. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 

<p>
A menubar is one of the most visible parts of the GUI application. 
It is a group of commands located in various menus. While in console 
applications you had to remember all those arcane commands, here we have 
most of the commands grouped into logical parts. There are accepted standards
that further reduce the amount of time spending to learn a new application.
Menus group commands that we can use in an application. 
Toolbars provide a quick access to the most frequently used commands.
</p>


<h2>Simple menu</h2>

<p>
The first example will show a simple menu. 
</p>

<pre class="code">
#!/usr/local/bin/jython
# -*- coding: utf-8 -*-

"""
ZetCode Jython Swing tutorial

This program creates a simple
menu.

author: Jan Bodnar
website: www.zetcode.com
last modified: November 2010
"""

from java.awt.event import KeyEvent
from java.lang import System
from javax.swing import ImageIcon
from javax.swing import JFrame
from javax.swing import JMenu
from javax.swing import JMenuBar
from javax.swing import JMenuItem


class Example(JFrame):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        menubar = JMenuBar()
        icon = ImageIcon("exit.png")

        file = JMenu("File")
        file.setMnemonic(KeyEvent.VK_F)

        fileExit = JMenuItem("Exit", icon,
            actionPerformed=self.onSelect)
        fileExit.setMnemonic(KeyEvent.VK_C)
        fileExit.setToolTipText("Exit application")

        file.add(fileExit)

        menubar.add(file)

        self.setJMenuBar(menubar)

        self.setTitle("Simple menu")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(250, 200)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def onSelect(self, e):
        System.exit(0)


if __name__ == '__main__':
    Example()
</pre>

<p>
Our example will show a menu with one item. By selecting the 
exit menu item we close the application. 
</p>

<pre class="explanation">
menubar = JMenuBar()
</pre>

<p>
Here we create a menubar.
</p>

<pre class="explanation">
icon = ImageIcon("exit.png")
</pre>

<p>
We will display an icon in the menu item.
</p>

<pre class="explanation">
file = JMenu("File")
file.setMnemonic(KeyEvent.VK_F)
</pre>

<p>
We create a menu object. A menu is a popup window containing <code>JMenuItems</code>.
Menus are located on the menubar. The menus can be accessed via the keybord as well. 
To bind a menu to a particular key, we use the <code>setMnemonic()</code> method. In our case, 
the menu can be opened with the ALT + F shortcut.
</p>

<pre class="explanation">
fileExit = JMenuItem("Exit", icon,
    actionPerformed=self.onSelect)
fileExit.setMnemonic(KeyEvent.VK_C)
fileExit.setToolTipText("Exit application")
</pre>

<p>
Here we create a <code>JMenuItem</code>. A menu item is an object shown in
a popup window of the selected menu. We also provide a shortcut for the menu
item and a tooltip as well. 
</p>

<pre class="explanation">
file.add(fileExit)
</pre>

<p>
A menu item is added to the menu. 
</p>

<pre class="explanation">
menubar.add(file)
</pre>

<p>
A menu is added to the menubar. 
</p>

<br>
<img src="/img/gui/jrubyswing/simplemenu.png" alt="Simple menu">
<div class="figure">Figure: Simple menu</div>


<h2>Submenu</h2>

<p>
A submenu is a menu plugged into another menu object. 
The next example demonstrates this. 
</p>

<pre class="code">
#!/usr/local/bin/jython
# -*- coding: utf-8 -*-

"""
ZetCode Jython Swing tutorial

This program creates a simple
submenu.

author: Jan Bodnar
website: www.zetcode.com
last modified: November 2010
"""

from java.lang import System
from java.awt.event import KeyEvent
from java.awt.event import ActionEvent
from javax.swing import JFrame
from javax.swing import JMenuBar
from javax.swing import JMenuItem
from javax.swing import JMenu
from javax.swing import ImageIcon
from javax.swing import KeyStroke


class Example(JFrame):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        menubar = JMenuBar()

        iconNew = ImageIcon("new.png")
        iconOpen = ImageIcon("open.png")
        iconSave = ImageIcon("save.png")
        iconExit = ImageIcon("exit.png")

        file = JMenu("File")
        file.setMnemonic(KeyEvent.VK_F)

        imp = JMenu("Import")
        imp.setMnemonic(KeyEvent.VK_M)

        newsf = JMenuItem("Import newsfeed list...")
        bookm = JMenuItem("Import bookmarks...")
        mail = JMenuItem("Import mail...")

        imp.add(newsf)
        imp.add(bookm)
        imp.add(mail)

        fileNew = JMenuItem("New", iconNew)
        fileNew.setMnemonic(KeyEvent.VK_N)

        fileOpen = JMenuItem("Open", iconOpen)
        fileNew.setMnemonic(KeyEvent.VK_O)

        fileSave = JMenuItem("Save", iconSave)
        fileSave.setMnemonic(KeyEvent.VK_S)

        fileExit = JMenuItem("Exit", iconExit,
            actionPerformed=self.onSelect)
        fileExit.setMnemonic(KeyEvent.VK_C)
        fileExit.setToolTipText("Exit application")
        fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
            ActionEvent.CTRL_MASK))

        file.add(fileNew)
        file.add(fileOpen)
        file.add(fileSave)
        file.addSeparator()
        file.add(imp)
        file.addSeparator()
        file.add(fileExit)

        menubar.add(file)

        self.setJMenuBar(menubar)

        self.setTitle("Submenu")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(320, 220)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def onSelect(self, e):
        System.exit(0)


if __name__ == '__main__':
    Example()
</pre>

<p>
In the example, we have three options in a submenu of a file menu. 
</p>


<pre class="explanation">
imp = JMenu("Import")
...
file.add(imp)
</pre>

<p>
A submenu is just like any other normal menu. It is created the 
same way. We simply add a menu to existing menu.
</p>

<pre class="explanation">
fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
    ActionEvent.CTRL_MASK))
</pre>

<p>
An accelerator is a key shortcut that launches a menu item. 
In our case, by pressing Ctrl + W we close the application.
</p>

<pre class="explanation">
file.addSeparator()
</pre>

<p>
A separator is a horizontal line that visually separates the menu items. 
This way we can group items into some logical places.
</p>

<br>
<img src="/img/gui/jrubyswing/submenu.png" alt="Submenu">
<div class="figure">Figure: Submenu</div>


<h2>Popup menu</h2>

<p>
In the next example, we create a popup menu. 
</p>

<pre class="code">
#!/usr/local/bin/jython
# -*- coding: utf-8 -*-

"""
ZetCode Jython Swing tutorial

This program creates a popup menu.

author: Jan Bodnar
website: www.zetcode.com
last modified: November 2010
"""

from java.awt.event import MouseListener
from java.lang import System
from javax.swing import JFrame
from javax.swing import JMenuItem
from javax.swing import JPopupMenu


class Example(JFrame, MouseListener):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.menu = JPopupMenu()
        menuItemBeep = JMenuItem("Beep", actionPerformed=self.onBeep)

        self.menu.add(menuItemBeep)

        menuItemClose = JMenuItem("Exit", actionPerformed=self.onExit)
        self.menu.add(menuItemClose);
        self.addMouseListener(self)

        self.setTitle("Popup menu")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(250, 200)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def mouseReleased(self, e):
        if e.getButton() == e.BUTTON3:
            self.menu.show(e.getComponent(), e.getX(), e.getY())

    def onExit(self, e):
        System.exit(0)

    def onBeep(self, e):
        toolkit = self.getToolkit()
        toolkit.beep()

if __name__ == '__main__':
    Example()
</pre>

<p>
In our example, we create a popup menu with two 
menu items. 
</p>

<pre class="explanation">
self.menu = JPopupMenu()
menuItemBeep = JMenuItem("Beep", actionPerformed=self.onBeep)
</pre>

<p>
We create a popup menu and a menu item. 
</p>

<pre class="explanation">
def mouseReleased(self, e):
    if e.getButton() == e.BUTTON3:
        self.menu.show(e.getComponent(), e.getX(), e.getY())
</pre>

<p>
We show the popup menu window at the x, y coordinates of
the mouse click. 
</p>


<br>
<img src="/img/gui/jrubyswing/popupmenu.png" alt="Popup menu`">
<div class="figure">Figure: Popup menu</div>



<h2>JToolbar</h2>

<p>
Menus group commands that we can use in an application. Toolbars provide 
a quick access to the most frequently used commands. In Swing, the 
<code>JToolBar</code> class creates a toolbar in an application.
</p>

<pre class="code">
#!/usr/local/bin/jython
# -*- coding: utf-8 -*-

"""
ZetCode Jython Swing tutorial

In this program, we create a simple
toolbar.

author: Jan Bodnar
website: www.zetcode.com
last modified: November 2010
"""


from java.awt import BorderLayout
from java.lang import System
from javax.swing import ImageIcon
from javax.swing import JFrame
from javax.swing import JMenu
from javax.swing import JMenuBar
from javax.swing import JToolBar
from javax.swing import JButton



class Example(JFrame):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        menubar = JMenuBar()
        file = JMenu("File")
        menubar.add(file)
        self.setJMenuBar(menubar)

        toolbar = JToolBar()

        icon = ImageIcon("exit.png")

        exitButton = JButton(icon, actionPerformed=self.onClick)
        toolbar.add(exitButton)

        self.add(toolbar, BorderLayout.NORTH)

        self.setTitle("Toolbar")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(350, 250)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def onClick(self, e):
        System.exit(0)

if __name__ == '__main__':
    Example()
</pre>

<p>
The example creates a toolbar with one exit button.
</p>

<pre class="explanation">
toolbar = JToolBar()
</pre>

<p>
A toolbar is created.
</p>

<pre class="explanation">
exitButton = JButton(icon, actionPerformed=self.onClick)
toolbar.add(exitButton)
</pre>

<p>
We create a button and add it to the toolbar.
</p>

<pre class="explanation">
self.add(toolbar, BorderLayout.NORTH)
</pre>

<p>
The toolbar is placed into the north part of the <code>BorderLayout</code>
manager.
</p>


<br>
<img src="/img/gui/jrubyswing/toolbar.png" alt="Toolbar">
<div class="figure">Figure: Toolbar</div>

<hr class="btm">

<p>
In this part of the Jython Swing tutorial, we mentioned menus and toolbars. 
</p>


<br>
<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 14, 2010  <span class="copyright">&copy; 2007 - 2012 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

